<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI图像生成器</title>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  
  <!-- 配置Tailwind自定义颜色和字体 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#6C5CE7', // 主色调：科技紫
            secondary: '#00CEFF', // 辅助色：科技蓝
            dark: '#1A1A2E', // 深色背景
            darker: '#121224', // 更深色背景
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  
  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .text-shadow {
        text-shadow: 0 0 10px rgba(108, 92, 231, 0.7);
      }
      .glow {
        box-shadow: 0 0 15px rgba(108, 92, 231, 0.5);
      }
      .bg-grid {
        background-image: linear-gradient(rgba(108, 92, 231, 0.1) 1px, transparent 1px),
                          linear-gradient(90deg, rgba(108, 92, 231, 0.1) 1px, transparent 1px);
        background-size: 20px 20px;
      }
    }
  </style>
  
  <style>
    /* 基础动画定义 */
    @keyframes pulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.5; }
    }
    
    @keyframes float {
      0%, 100% { transform: translateY(0); }
      50% { transform: translateY(-10px); }
    }
    
    @keyframes gradientShift {
      0% { background-position: 0% 50%; }
      50% { background-position: 100% 50%; }
      100% { background-position: 0% 50%; }
    }
    
    .animate-float {
      animation: float 6s ease-in-out infinite;
    }
    
    .gradient-text {
      background: linear-gradient(90deg, #6C5CE7, #00CEFF);
      background-size: 200% 200%;
      animation: gradientShift 3s ease infinite;
      -webkit-background-clip: text;
      background-clip: text;
      color: transparent;
    }
    
    /* 加载动画 */
    .loader {
      width: 48px;
      height: 48px;
      border: 5px solid rgba(108, 92, 231, 0.2);
      border-bottom-color: #6C5CE7;
      border-radius: 50%;
      animation: rotation 1s linear infinite;
    }
    
    @keyframes rotation {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
    
    /* 图片放大浮层样式 */
    .image-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-color: rgba(0, 0, 0, 0.65);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
      opacity: 0;
      visibility: hidden;
      transition: opacity 0.3s ease, visibility 0.3s ease;
      padding: 20px;
    }
    
    .image-overlay.active {
      opacity: 1;
      visibility: visible;
    }
    
    .overlay-content {
      position: relative;
      max-width: 100%;
      max-height: 100%;
    }
    
    .overlay-image {
      max-width: 100%;
      max-height: 90vh;
      object-contain;
      border-radius: 8px;
    }
    
    .close-btn {
      position: absolute;
      top: -40px;
      right: 0;
      color: white;
      background: none;
      border: none;
      font-size: 24px;
      cursor: pointer;
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.1);
      transition: background-color 0.3s ease;
      z-index: 1001;
    }
    
    .close-btn:hover {
      background-color: rgba(255, 255, 255, 0.2);
    }
    
    /* 历史图片样式 */
    .history-image-item {
      position: relative;
      overflow: hidden;
    }
    
    /* 可点击图片样式 */
    .clickable-image {
      cursor: zoom-in;
      transition: transform 0.3s ease;
    }
    
    .clickable-image:hover {
      transform: scale(1.02);
    }

    /* 错误提示样式 */
    .error-toast {
      position: fixed;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      background-color: #ff4444;
      color: white;
      padding: 10px 20px;
      border-radius: 4px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.2);
      z-index: 100;
      opacity: 0;
      transition: opacity 0.3s ease;
    }
    
    .error-toast.show {
      opacity: 1;
    }
  </style>
</head>
<body class="bg-dark text-gray-100 min-h-screen bg-grid">
  <!-- 错误提示框 -->
  <div id="errorToast" class="error-toast">错误信息</div>
  
  <!-- 图片放大浮层 -->
  <div id="imageOverlay" class="image-overlay">
    <div class="overlay-content">
      <button id="closeOverlay" class="close-btn" aria-label="关闭图片查看">
        <i class="fa fa-times"></i>
      </button>
      <img id="overlayImage" src="" alt="大图预览" class="overlay-image">
    </div>
  </div>
  
  <!-- 页面容器 -->
  <div class="container mx-auto px-4 py-8 max-w-5xl">
    <!-- 标题区域 -->
    <header class="text-center mb-10">
      <h1 class="text-[clamp(1.8rem,5vw,3rem)] font-bold gradient-text mb-2 animate-pulse">
        AI图像生成器
      </h1>
      <p class="text-gray-400 text-[clamp(0.9rem,2vw,1.1rem)] max-w-2xl mx-auto">
        通过提示词生成独特图像，释放你的创造力
      </p>
    </header>
    
    <!-- 主内容区域 -->
    <main>
      <!-- 表单区域 -->
      <section class="bg-darker rounded-2xl p-6 md:p-8 mb-10 border border-primary/20 glow">
        <form id="promptForm" class="space-y-6">
          <!-- 正向提示词 -->
          <div class="space-y-2">
            <label for="positivePrompt" class="block text-secondary font-medium flex items-center">
              <i class="fa fa-plus-circle mr-2"></i>正向提示词
            </label>
            <div class="relative">
              <textarea id="positivePrompt" class="w-full bg-dark border border-primary/30 rounded-lg p-4 min-h-[100px] resize-y focus:outline-none focus:border-primary transition-all" placeholder="描述你想要生成的图像特征，例如：一只戴着帽子的猫，超现实主义风格，高细节..."></textarea>
              <button type="button" class="text-primary hover:text-secondary absolute right-3 bottom-3 transition-colors" onclick="resizeTextarea('positivePrompt', this)" aria-label="放大缩小文本框">
                <i class="fa fa-expand"></i>
              </button>
            </div>
          </div>
          
          <!-- 负向提示词 -->
          <div class="space-y-2">
            <label for="negativePrompt" class="block text-secondary font-medium flex items-center">
              <i class="fa fa-minus-circle mr-2"></i>负向提示词
            </label>
            <div class="relative">
              <textarea id="negativePrompt" class="w-full bg-dark border border-primary/30 rounded-lg p-4 min-h-[100px] resize-y focus:outline-none focus:border-primary transition-all" placeholder="描述你不想要的图像特征，例如：模糊，低细节，水印..."></textarea>
              <button type="button" class="text-primary hover:text-secondary absolute right-3 bottom-3 transition-colors" onclick="resizeTextarea('negativePrompt', this)" aria-label="放大缩小文本框">
                <i class="fa fa-expand"></i>
              </button>
            </div>
          </div>
          
          <!-- 提交按钮 -->
          <div class="text-center pt-4">
            <button type="submit" id="generateBtn" class="bg-gradient-to-r from-primary to-secondary text-white font-bold py-3 px-8 rounded-full hover:opacity-90 transform hover:scale-105 transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 focus:ring-offset-dark">
              <i class="fa fa-magic mr-2"></i>一键生成
            </button>
          </div>
        </form>
      </section>
      
      <!-- 图片展示区域 -->
      <section class="bg-darker rounded-2xl p-6 md:p-8 border border-primary/20 overflow-hidden mb-10">
        <h2 class="text-xl font-semibold mb-4 text-secondary">生成结果</h2>
        
        <div id="imageContainer" class="relative bg-dark rounded-xl min-h-[300px] flex items-center justify-center overflow-hidden">
          <!-- 初始状态提示 -->
          <div id="initialState" class="text-center p-6">
            <div class="animate-float text-primary/50 mb-4">
              <i class="fa fa-image text-5xl"></i>
            </div>
            <p class="text-gray-400">点击"一键生成"按钮开始创建图像</p>
          </div>
          
          <!-- 加载状态 -->
          <div id="loadingState" class="text-center p-6 hidden">
            <div class="loader mx-auto mb-4"></div>
            <p class="text-gray-300 mb-2">正在生成图像，请稍候...</p>
            <p class="text-primary font-medium" id="loadingProgress">
              处理中，请稍候...
            </p>
          </div>
          
          <!-- 图片结果 -->
          <div id="resultState" class="w-full h-full hidden">
            <div class="w-full h-full flex items-center justify-center">
              <img id="generatedImage" src="" alt="生成的图像" class="max-w-full max-h-full object-contain clickable-image" onclick="openImageOverlay(this.src)" aria-label="点击查看大图">
            </div>
          </div>
        </div>
      </section>
      
      <!-- 历史出图列表区域 -->
      <section class="bg-darker rounded-2xl p-6 md:p-8 border border-primary/20 mb-10">
        <h2 class="text-xl font-semibold mb-6 text-secondary flex items-center">
          <i class="fa fa-history mr-2"></i>历史生成记录
        </h2>
        
        <!-- 历史图片网格 -->
        <div id="historyGrid" class="grid grid-cols-2 md:grid-cols-3 gap-4 mb-6">
          <!-- 历史图片将通过JavaScript动态添加 -->
        </div>
        
        <!-- 加载更多提示 -->
        <div id="loadMoreIndicator" class="flex justify-center items-center py-4">
          <div class="loader hidden" id="historyLoader"></div>
          <p class="text-gray-400 text-sm hidden" id="noMoreData">没有更多历史记录了</p>
        </div>
        
        <!-- 用于检测滚动到底部的触发器 -->
        <div id="scrollTrigger" class="h-10"></div>
      </section>
    </main>
    
    <!-- 页脚 -->
    <footer class="mt-12 text-center text-gray-500 text-sm">
      <p>© 2025 AI图像生成工具 | 公众号专用</p>
    </footer>
  </div>
  
  <script>
    // 全局变量
    let currentPage = 1;
    const pageSize = 6; // 每页加载6张图片
    let isLoading = false;
    let hasMoreData = true;
    let pollInterval = null; // 轮询定时器
    let pollCount = 0; // 轮询次数计数器
    const maxPollCount = 20; // 最大轮询次数（20次 x 3秒 = 60秒超时）
    let user_id = ''; // 存储从URL获取的user_id
    
    // DOM元素
    const imageOverlay = document.getElementById('imageOverlay');
    const overlayImage = document.getElementById('overlayImage');
    const closeOverlay = document.getElementById('closeOverlay');
    const loadingState = document.getElementById('loadingState');
    const loadingProgress = document.getElementById('loadingProgress');
    
    // 初始化浮层事件
    function initOverlayEvents() {
      // 关闭按钮点击事件
      closeOverlay.addEventListener('click', closeImageOverlay);
      
      // 点击浮层背景关闭
      imageOverlay.addEventListener('click', function(e) {
        if (e.target === imageOverlay) {
          closeImageOverlay();
        }
      });
      
      // 键盘ESC关闭
      document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && imageOverlay.classList.contains('active')) {
          closeImageOverlay();
        }
      });
    }
    
    // 打开图片浮层
    function openImageOverlay(imageUrl) {
      console.log('打开图片浮层:', imageUrl);
      overlayImage.src = imageUrl;
      imageOverlay.classList.add('active');
      document.body.style.overflow = 'hidden'; // 禁止背景滚动
    }
    
    // 关闭图片浮层
    function closeImageOverlay() {
      imageOverlay.classList.remove('active');
      document.body.style.overflow = ''; // 恢复滚动
    }
    
    // 从URL中获取参数
    function getUrlParameter(name) {
      name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
      const regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
      const results = regex.exec(location.search);
      return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }
    // 从path 获取参数
    function getUserIdFromPath() {
      // 解析当前URL的路径部分（例如："/user/oQpde1U_ca6pTNGcH_UuGnZiDCOw"）
      const path = window.location.pathname;
      // 匹配 "/user/xxx" 格式的路径，提取xxx部分
      const pathRegex = /^\/user\/([^\/]+)$/;
      const match = path.match(pathRegex);
      
      if (match && match[1]) {
        // 提取并解码user_id（处理可能的特殊字符）
        return decodeURIComponent(match[1]);
      }
      return ''; // 未匹配到则返回空
    }

    // 页面加载时初始化
    window.addEventListener('DOMContentLoaded', () => {
      // user_id = getUrlParameter('user_id');
      // console.log('获取到的user_id:', user_id);
      user_id = getUserIdFromPath();
      console.log('从路径获取到的user_id:', user_id);

      // 初始化浮层事件
      initOverlayEvents();
      
      // 加载第一页历史图片
      fetchHistoryImages();
      
      // 设置滚动加载
      setupInfiniteScroll();
    });
    
    // 显示错误提示
    function showError(message) {
      const errorToast = document.getElementById('errorToast');
      errorToast.textContent = message;
      errorToast.classList.add('show');
      
      // 3秒后隐藏错误提示
      setTimeout(() => {
        errorToast.classList.remove('show');
      }, 3000);
    }
    
    // 文本框放大缩小功能
    function resizeTextarea(textareaId, button) {
      const textarea = document.getElementById(textareaId);
      const isExpanded = textarea.classList.contains('min-h-[300px]');
      
      if (isExpanded) {
        textarea.classList.remove('min-h-[300px]');
        textarea.classList.add('min-h-[100px]');
        button.innerHTML = '<i class="fa fa-expand"></i>';
      } else {
        textarea.classList.remove('min-h-[100px]');
        textarea.classList.add('min-h-[300px]');
        button.innerHTML = '<i class="fa fa-compress"></i>';
      }
    }
    
    // 表单提交处理
    document.getElementById('promptForm').addEventListener('submit', function(e) {
      e.preventDefault();
      
      // 获取表单数据
      const positivePrompt = document.getElementById('positivePrompt').value;
      const negativePrompt = document.getElementById('negativePrompt').value;
      
      // 验证输入
      if (!positivePrompt.trim()) {
        showError('请输入正向提示词');
        return;
      }
      
      // 显示加载状态
      document.getElementById('initialState').classList.add('hidden');
      document.getElementById('resultState').classList.add('hidden');
      loadingState.classList.remove('hidden');
      
      // 禁用生成按钮
      document.getElementById('generateBtn').disabled = true;
      document.getElementById('generateBtn').classList.add('opacity-70', 'cursor-not-allowed');
      
      // 重置轮询计数器
      pollCount = 0;
      
      // 调用创建任务接口
      createTask(positivePrompt, negativePrompt)
        .then(taskId => {
          console.log('任务创建成功，taskId:', taskId);
          // 开始轮询任务状态
          startPollingTaskStatus(taskId);
        })
        .catch(error => {
          console.error('任务创建失败:', error);
          showError('创建任务失败: ' + error.message);
          // 恢复初始状态
          resetToInitialState();
        });
    });
    
    // 创建任务接口调用
    function createTask(positive, negative) {
      return new Promise((resolve, reject) => {
        const apiUrl = 'https://image.jbdhm.icu/api/tasks';
        console.log('创建任务请求:', apiUrl);
        
        const requestData = {
          biz: 'h5',
          title: 'h5作图',
          desc: positive,
          count: 1,
          negative: negative
        };
        
        if (user_id) {
          requestData.user_id = user_id;
        }
        
        fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(requestData)
        })
        .then(response => {
          console.log('创建任务响应状态:', response.status);
          if (!response.ok) {
            return response.text().then(text => {
              throw new Error(`HTTP错误: ${response.status}，内容: ${text}`);
            });
          }
          return response.json().catch(() => {
            throw new Error('接口返回格式不是JSON');
          });
        })
        .then(data => {
          console.log('创建任务响应数据:', data);
          if (data.task && data.task.id) {
            resolve(data.task.id);
          } else {
            reject(new Error('接口未返回有效的task_id'));
          }
        })
        .catch(error => {
          reject(error);
        });
      });
    }
    
    // 开始轮询任务状态
    function startPollingTaskStatus(taskId) {
      // 清除可能存在的旧定时器
      if (pollInterval) {
        clearInterval(pollInterval);
      }
      
      // 立即查询一次
      checkTaskStatus(taskId)
        .then(result => {
          if (result.completed) {
            handleTaskCompleted(result.imageUrl);
            return;
          }
          
          // 未完成，开始定时轮询（每3秒一次）
          pollInterval = setInterval(() => {
            // 检查是否超过最大轮询次数
            if (pollCount >= maxPollCount) {
              clearInterval(pollInterval);
              showError('任务处理超时，请重试');
              resetToInitialState();
              return;
            }
            
            pollCount++;
            // 更新加载进度显示
            updateLoadingProgress(pollCount);
            
            checkTaskStatus(taskId)
              .then(result => {
                if (result.completed) {
                  clearInterval(pollInterval);
                  handleTaskCompleted(result.imageUrl);
                } else if (result.failed) {
                  clearInterval(pollInterval);
                  showError('任务处理失败: ' + (result.error || '未知错误'));
                  resetToInitialState();
                }
              })
              .catch(error => {
                clearInterval(pollInterval);
                console.error('轮询任务状态失败:', error);
                showError('查询任务状态失败: ' + error.message);
                resetToInitialState();
              });
          }, 3000); // 每3秒轮询一次
        })
        .catch(error => {
          console.error('查询任务状态失败:', error);
          showError('查询任务状态失败: ' + error.message);
          resetToInitialState();
        });
    }
    
    // 更新加载进度显示
    function updateLoadingProgress(count) {
      const totalSeconds = maxPollCount * 3;
      const elapsedSeconds = count * 3;
      const remainingSeconds = totalSeconds - elapsedSeconds;
      loadingProgress.textContent = `处理中，请稍候... (剩余约 ${remainingSeconds} 秒)`;
    }
    
    // 检查任务状态接口调用
    function checkTaskStatus(taskId) {
      return new Promise((resolve, reject) => {
        let apiUrl = `https://image.jbdhm.icu/api/tasks/${taskId}`;
        
        if (user_id) {
          apiUrl += `?user_id=${encodeURIComponent(user_id)}`;
        }
        
        console.log('查询任务状态请求:', apiUrl);
        
        fetch(apiUrl, {
          method: 'GET',
          headers: {
            // 如有需要，添加认证信息
          }
        })
        .then(response => {
          console.log('查询任务状态响应状态:', response.status);
          if (!response.ok) {
            return response.text().then(text => {
              throw new Error(`HTTP错误: ${response.status}，内容: ${text}`);
            });
          }
          return response.json().catch(() => {
            throw new Error('接口返回格式不是JSON');
          });
        })
        .then(data => {
          console.log('查询任务状态响应数据:', data);
          if (data.status === 'COMPLETED' && data.result && data.result.image && data.result.image[0]) {
            resolve({ completed: true, imageUrl: data.result.image[0] });
          } else if (data.status === 'FAILED') {
            resolve({ failed: true, error: data.result ? data.result.error_msg : '未知错误' });
          } else {
            resolve({ completed: false });
          }
        })
        .catch(error => {
          reject(error);
        });
      });
    }
    
    // 处理任务完成
    function handleTaskCompleted(imageUrl) {
      // 确保loading状态隐藏
      loadingState.classList.add('hidden');
      
      // 显示生成的图片
      const imgElement = document.getElementById('generatedImage');
      imgElement.src = imageUrl;
      document.getElementById('resultState').classList.remove('hidden');
      
      // 启用生成按钮
      document.getElementById('generateBtn').disabled = false;
      document.getElementById('generateBtn').classList.remove('opacity-70', 'cursor-not-allowed');
      
      // 刷新历史列表
      refreshHistoryList();
    }
    
    // 重置到初始状态
    function resetToInitialState() {
      // 确保loading状态隐藏
      loadingState.classList.add('hidden');
      
      document.getElementById('resultState').classList.add('hidden');
      document.getElementById('initialState').classList.remove('hidden');
      
      // 启用生成按钮
      document.getElementById('generateBtn').disabled = false;
      document.getElementById('generateBtn').classList.remove('opacity-70', 'cursor-not-allowed');
    }
    
    // 获取历史图片列表
    function fetchHistoryImages(page = 1, size = pageSize, isRefresh = false) {
      if (isLoading || (!isRefresh && !hasMoreData)) return;
      
      isLoading = true;
      document.getElementById('historyLoader').classList.remove('hidden');
      
      let apiUrl = `https://image.jbdhm.icu/api/tasks?page=${page}&page_size=${size}`;
      // if (user_id) {
      //   apiUrl += `&user_id=${encodeURIComponent(user_id)}`;
      // }
      
      console.log('获取历史记录请求:', apiUrl);
      
      fetch(apiUrl, {
        method: 'GET',
        headers: {
          // 如有需要，添加认证信息
          'user_id': user_id
        },
        timeout: 20000 // 20秒超时
      })
      .then(response => {
        console.log('获取历史记录响应状态:', response.status);
        if (!response.ok) {
          return response.text().then(text => {
            throw new Error(`HTTP错误: ${response.status}，内容: ${text}`);
          });
        }
        return response.json().catch(() => {
          throw new Error('接口返回格式不是JSON');
        });
      })
      .then(data => {
        console.log('获取历史记录响应数据:', data);
        
        if (!data.data || !Array.isArray(data.data.tasks)) {
          throw new Error('接口返回格式不正确，缺少tasks数组');
        }
        
        const historyGrid = document.getElementById('historyGrid');
        
        if (isRefresh) {
          historyGrid.innerHTML = '';
        }
        
        const completedTasks = data.data.tasks.filter(task => 
          task.status === 'COMPLETED' && 
          task.result && 
          task.result.image && 
          Array.isArray(task.result.image) && 
          task.result.image[0]
        );
        
        if (completedTasks.length > 0) {
          completedTasks.forEach(task => {
            const imageItem = document.createElement('div');
            imageItem.className = 'history-image-item rounded-lg overflow-hidden border border-primary/20';
            
            const date = new Date(task.create_time);
            const formattedDate = `${date.getMonth()+1}月${date.getDate()}日 ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
            
            const imgContainer = document.createElement('div');
            imgContainer.className = 'relative';
            imgContainer.innerHTML = `
              <img src="${task.result.image[0]}" alt="历史生成图像: ${task.desc.substring(0, 20)}..." class="w-full h-48 object-cover clickable-image">
              <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-darker to-transparent p-2 text-xs text-gray-300">
                ${formattedDate}
              </div>
            `;
            
            const imgElement = imgContainer.querySelector('img');
            imgElement.addEventListener('click', function() {
              openImageOverlay(this.src);
            });
            
            imageItem.appendChild(imgContainer);
            historyGrid.appendChild(imageItem);
          });
        } else if (isRefresh) {
          historyGrid.innerHTML = `
            <div class="col-span-2 md:col-span-3 text-center py-10 text-gray-400">
              <i class="fa fa-folder-open-o text-4xl mb-3"></i>
              <p>暂无历史生成记录</p>
            </div>
          `;
        }
        
        if (data.pagination) {
          currentPage = data.pagination.page;
          hasMoreData = data.pagination.has_next;
        } else {
          currentPage = page;
          hasMoreData = data.data.tasks.length >= size;
        }
      })
      .catch(error => {
        console.error('获取历史记录错误:', error);
        showError('加载历史记录失败: ' + error.message);
        if (currentPage === 1) {
          document.getElementById('historyGrid').innerHTML = `
            <div class="col-span-2 md:col-span-3 text-center py-10 text-gray-400">
              <i class="fa fa-exclamation-triangle text-4xl mb-3 text-yellow-500"></i>
              <p>加载历史记录失败</p>
              <p class="text-sm mt-2">${error.message}</p>
            </div>
          `;
        }
      })
      .finally(() => {
        isLoading = false;
        document.getElementById('historyLoader').classList.add('hidden');
        
        if (!hasMoreData && currentPage > 1) {
          document.getElementById('noMoreData').classList.remove('hidden');
        } else {
          document.getElementById('noMoreData').classList.add('hidden');
        }
      });
    }
    
    // 刷新历史列表
    function refreshHistoryList() {
      currentPage = 1;
      hasMoreData = true;
      fetchHistoryImages(1, pageSize, true);
    }
    
    // 滚动加载更多
    function setupInfiniteScroll() {
      const observer = new IntersectionObserver((entries) => {
        const [entry] = entries;
        if (entry.isIntersecting && !isLoading && hasMoreData) {
          fetchHistoryImages(currentPage + 1, pageSize);
        }
      }, { threshold: 0.1 });
      
      observer.observe(document.getElementById('scrollTrigger'));
    }
  </script>
</body>
</html>
